import type { TBody, TParams } from '@/types';
import type {
  IMenu,
  IPagination,
  IPermission,
  IRole,
  IRoleStatistics,
  IUser,
} from '@/interfaces';
import { createConfig, getQueryParams, handleReqMiddleware } from '@/lib/api';

export const queryAllRole = (
  params?: TParams,
): Promise<Response | IPagination<IRole>> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL + `/roles?${getQueryParams(config)}`,
    config,
  ).then(handleReqMiddleware);
};

export const queryRoleDetails = (
  params?: TParams,
): Promise<Response | IRole> => {
  const config = createConfig(params);
  return fetch(config.baseURL + `/roles/${config.id}`, config).then(
    handleReqMiddleware,
  );
};

export const queryRoleUsersById = (
  params?: TParams,
): Promise<Response | IPagination<IUser>> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL + `/roles/${config.id}/users?${getQueryParams(config)}`,
    config,
  ).then(handleReqMiddleware);
};

export const queryRolePermissionsById = (
  params?: TParams,
): Promise<Response | IPagination<IPermission>> => {
  const config = createConfig(params);
  return fetch(
    config.baseURL +
      `/roles/${config.id}/permissions?${getQueryParams(config)}`,
    config,
  ).then(handleReqMiddleware);
};

export const queryRoleMenusById = (
  params?: TParams,
): Promise<Response | IMenu[]> => {
  const config = createConfig(params);
  return fetch(config.baseURL + `/roles/${config.id}/menus`, config).then(
    handleReqMiddleware,
  );
};

export const queryRoleStatistics = (
  params?: TParams,
): Promise<Response | IRoleStatistics> => {
  const config = createConfig(params);
  return fetch(config.baseURL + '/roles/statistics', config).then(
    handleReqMiddleware,
  );
};

export const createRole = (
  params: TBody<{
    name: string;
  }>,
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'POST' });
  return fetch(config.baseURL + '/roles', config).then(handleReqMiddleware);
};

export const updateRole = (
  params: TBody<{
    name?: string;
    sort?: number;
    hide?: boolean;
  }>,
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'PUT' });
  return fetch(config.baseURL + `/roles/${config.id}`, config).then(
    handleReqMiddleware,
  );
};

export const assignRole = (
  params: TBody<{
    userId: string;
  }>,
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'PUT' });
  return fetch(config.baseURL + `/roles/${config.id}/assign`, config).then(
    handleReqMiddleware,
  );
};

export const unAssignRole = (
  params: TBody<{
    userId: string;
  }>,
): Promise<Response | void> => {
  const config = createConfig(params, { method: 'DELETE' });
  return fetch(
    config.baseURL + `/roles/${config.id}/assign?${getQueryParams(config)}`,
    config,
  ).then(handleReqMiddleware);
};
